<?php
/**
 * 关注
 *
 * User: kaikaic
 * Date: 2018/12/5
 * Time: 17:05
 */

namespace app\api\controller;

use app\psy\service\ConsultantService;
use app\psy\service\FollowService;
use app\psy\service\OrganizationService;
use controller\BasicApi;

class Follow extends BasicApi {

    /**
     * 关注
     * type=consult,咨询师;type=org,咨询机构
     * http://psy.game.com/api/follow/index?type=org&id=5
     */
    public function index() {
        $type = trim($this->request->param("type"));
        $id = intval($this->request->param("id"));
        $follow = intval($this->request->param("follow",0));
        $account_id = intval($this->request->param("account_id"));

        if (!$id || !$type) {
            $this->error("参数错误");
        }

        $type = strtolower($type);
        $typeArray = array('consult', 'org');
        if (!in_array($type, $typeArray)) {
            $this->error("类型错误");
        }

        //TODO 用户ID
        $accountID = $account_id;

        // 已关注，返回成功
        $params = array();
        $params['account_id'] = $accountID;
        $params['type'] = $type;
        $params['target_id'] = $id;

        $result = FollowService::getInstance()->single($params);
        if ($result) {
            FollowService::getInstance()->remove($params);
            $this->updateFollowNumber($params,'subtraction');
            $this->success('取关成功',0);
        }

        // 未关注，写入数据
        $params['create_time'] = time();
        $result = FollowService::getInstance()->insert($params);
        if ($result) {
            $this->updateFollowNumber($params,'add');
            $this->success('关注成功',1);
        }else {
            $this->error("关注失败，请稍后重试!", 0);
        }
    }

    /**
     * 更新关注数
     *
     * @param Array $follow,关注记录信息
     * @return bool
     */
    private function updateFollowNumber($follow,$type2) {
        $type = $follow['type'];
        $id = $follow['target_id'];

        if ($type == "consult") {
            $record = ConsultantService::getInstance()->find($id);
            if (!$record) {
                return false;
            }

            $update = array();
            if($type2=='add'){
                $update['follow'] = $record['follow'] + 1;
            }else{
                $update['follow'] = $record['follow'] -1;
            }


            return ConsultantService::getInstance()->update($update, $id);
        }

        if ($type == "org") {
            $record = OrganizationService::getInstance()->find($id);
            if (!$record) {
                return false;
            }

            $update = array();
            if($type2=='add'){
                $update['follow'] = $record['follow'] + 1;
            }else{
                $update['follow'] = $record['follow'] -1;
            }
            return OrganizationService::getInstance()->update($update, $id);
        }
    }
}